/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.dao.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import ar.com.greensoft.neo.dao.ObraSocialDao;
import ar.com.greensoft.neo.model.ObraSocial;
import ar.com.greensoft.neo.model.ObraSocial_;
import ar.com.greensoft.neo.search.SearchInput;
import ar.com.greensoft.neo.search.user.ObraSocialSearchInput;
import ar.com.greensoft.neo.util.SearchUtil;

/**
 * @author Jorge E. Villaverde
 *
 */
@Transactional
@Repository
public class JpaObraSocialDaoImpl extends AbstractJpaWithRevisionDaoImpl<ObraSocial> implements ObraSocialDao {

	@Override
	protected Class<ObraSocial> getEntityClazz() {
		return ObraSocial.class;
	}

	@Override
	protected String getCountNamedQuery() {
		return ObraSocial.COUNT_QUERY_NAME;
	}

	@Override
	protected String getListNamedQuery() {
		return ObraSocial.FIND_ALL_QUERY_NAME;
	}

	@Override
	protected Expression<Boolean> createWhereFromSearchInput(SearchInput input, Root<ObraSocial> root) {
		ObraSocialSearchInput ossi = (ObraSocialSearchInput)input;
		
		CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
		Predicate predicate = null;
		
		if(ossi.isBuscarNombre() && StringUtils.hasText(ossi.getNombre())){
			String searchText = SearchUtil.likeString(ossi.getNombre());
			predicate = criteriaBuilder.or(
					criteriaBuilder.like(root.get(ObraSocial_.name), searchText),
					criteriaBuilder.like(root.get(ObraSocial_.sigla), searchText),
					criteriaBuilder.like(root.get(ObraSocial_.web), searchText),
					criteriaBuilder.like(root.get(ObraSocial_.telefono1), searchText),
					criteriaBuilder.like(root.get(ObraSocial_.telefono2), searchText),
					criteriaBuilder.like(root.get(ObraSocial_.email), searchText));
		}
		return predicate;
	}

}
